from flask import render_template, redirect, url_for, flash, request, session
from . import auth_bp

# 模拟用户数据库
USERS = {
    'user1': {'password': 'pass1', 'name': 'User One'},
    'tzq': {'password': '1', 'name': 'tzq'},
    'user2': {'password': 'pass2', 'name': 'User Two'}
}


@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')

        # 验证用户
        if username in USERS and USERS[username]['password'] == password:
            session['user'] = username  # 创建会话
            flash('登录成功!', 'success')
            return redirect(url_for('auth.profile'))
        else:
            flash('用户名或密码错误', 'danger')

    return render_template('auth/login.html')


@auth_bp.route('/profile')
def profile():
    if 'user' not in session:
        flash('请先登录', 'warning')
        return redirect(url_for('auth.login'))

    user_data = USERS.get(session['user'])
    return render_template('auth/profile.html', user=user_data)


@auth_bp.route('/logout')
def logout():
    session.pop('user', None)  # 销毁会话
    flash('您已成功登出', 'info')
    return redirect(url_for('auth.login'))


